<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use app\admin\model\pt\Job;
use think\Db;
use app\common\library\pt\Config;

use think\Exception;
/**
 * 我的工作
 *
 * @icon fa fa-circle-o
 */
class JobOrder extends Backend
{

    /**
     * Job模型对象
     * @var \app\admin\model\pt\Job
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\JobOffer();
        $this->view->assign('responsibility', $this->model->getJobOfferResponsibilityList());
    }


    /**
     * 查看
     *
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 传递工作细项配置到前端
            $job_detail_conf = Config::getConfig(null, "job_details", "tabs");
            $this->view->assign("job_detail_conf", $job_detail_conf);
            return $this->view->fetch();
        }
        $title = Config::getConfig(null, "job_details", "tabs");
        //检查配置是否开启
        if (empty($title)) {
            $this->error('暂未配置工作细项');
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        //获取前端的参数
        $search = $this->request->get("search", '');

        //查询jobOffers
        $jobOffers = Db::name('pt_job_offer')
            ->alias('offer')
            ->join('pt_order order', 'offer.order_id = order.id')
            ->join('pt_job job', 'job.order_id = order.id')
            ->field('offer.order_id,order.pt_grade,order.user_name,order.district_name,order.agency_serial_no,job.title,job.position_name,offer.responsibility,job.job_code,job.worker_id,job.id as job_id,job.status')
            ->where('offer.user_id', $this->auth->id)
            ->where('offer.offer_status', 2)
            ->order('job.position_id asc')
            ->select();

        $orderIds = [];
        $name_order = [];
        if (!empty($jobOffers)) {
            foreach ($jobOffers as $v) {
                $orderIds[] = $v['order_id'];
                if (!empty($v['title']) && !empty($v['order_id'])) {
                    $name_order[$v['order_id'] . '_' . $v['title']] = $v;
                }
            }
        }
        //查询所有的job 记录
        // $job_status = [];
        //记录工作记录中某个员工的执行情况
        $jobs = Job::where('order_id', 'in', $orderIds)
            ->with('jobRecords')
            ->select();

        //某个订单 一项工作的执行情况
        $order_job_record = [];
        //某个订单某个工作 有多少个记录
        $order_job_records_count = [];
        foreach ($jobs as $v) {
            // 先提取 jobRecords 数据
            $records = $v['jobRecords'] ?? [];
            foreach ($records as $v1) {
                // 使用数组键来存储，如果有重复的会自动去重，只保留一条
                $key = $v['order_id'] . '_' . $v['title'] . '_' . $v1['submitter_id'];
                $order_job_record[$key] = true;
                $order_job_records_count[$v['order_id'] . '_' . $v['title']] = ($order_job_records_count[$v['order_id'] . '_' . $v['title']] ?? 0) + 1;
            }

            // 移除 jobRecords 字段
            unset($v['jobRecords']);
        }
        $orders = Db::name('pt_order')
            ->whereIn('id', $orderIds)
            ->field('id,user_name,pt_grade,agency_serial_no,order_status')
            ->paginate($limit);

        $result = [];
        foreach ($orders as $v) {
            // $v 已经是数组，不需要调用 toArray()
            $item = $v;
            $item['reassign'] = false;
            if ($this->isGroup('组长') || $this->isGroup('总监')) {
                $item['reassign'] = true;
            }
            foreach ($title as $itemTitle) {
                $key = $v['id'] . '_' . $itemTitle[0];  // 如 "1_教育经历"
                $orderData = $name_order[$key] ?? null;
                if($v['order_status'] == 5){
                    $status = '定稿上报';
                    $color = 'btn-blue';
                }else if($v['order_status'] == 6){
                    $status = '资格审查通过';
                    $color = 'btn-success';
                }else if($v['order_status'] == 9){
                    $status = '未通过';
                    $color = 'btn-purple';
                }else if($v['order_status'] == 10 || $v['order_status'] == 11){
                    $status = '已退费';
                    $color = 'btn-gray';
                }else{
                    if ($orderData) {
                        $status = '未开始';
                        $color = 'btn-default';
                        if(!empty($orderData['position_name'])){
                            $status = $orderData['position_name'].'处理中';
                        }
                        // 当前用户是负责人
                        if ($orderData["worker_id"] == $this->auth->id) {
                            $color = 'btn-danger';
                        } else {

                            // 判断是否已完成（有工作记录）
                            if ($order_job_record[$v['id'] . '_' . $itemTitle[0] . '_' . $this->auth->id] ?? false) {
                                $color = 'btn-warning';
                            }else{
                                if (isset($order_job_records_count[$v['id'] . '_' . $itemTitle[0]]) && $order_job_records_count[$v['id'] . '_' . $itemTitle[0]] > 0) {
                                    $status = '无需处理';
                                    $color = 'btn-default';
                                }
                            }

                        }

                        // 设置状态和颜色
                        $item['id'] = $v['id'];
                        $item['order_name'] = $v['user_name'] . '(' . $v['pt_grade'] . ')' . "申报";
                        $item['pt_grade'] = $v['pt_grade'];
                        $item[$itemTitle[1] . "status"] = $status;
                        $item[$itemTitle[1] . "color"] = $color;
                        // 设置 work_detail 信息
                        $item[$itemTitle[1] . "job_code"] = $orderData['job_code'];
                        $item[$itemTitle[1] . "work_detail_name"] = $orderData['title'];
                        $item[$itemTitle[1] . "job_id"] = $orderData['job_id'];
                    } else {
                        //工作和自己无关
                        $item['id'] = $v['id'];
                        $item['order_name'] = $v['user_name'] . '(' . $v['pt_grade'] . ')' . "申报";
                        $item['pt_grade'] = $v['pt_grade'];
                        $item[$itemTitle[1] . "status"] = "状态异常";
                        //无色
                        $item[$itemTitle[1] . "color"] = "";
                        $item[$itemTitle[1] . "job_code"] = "";
                        $item[$itemTitle[1] . "work_detail_name"] = "";
                        $item[$itemTitle[1] . "job_id"] = "";
                    }
                }

            }

            // ✅ 将处理后的 $item 添加到结果数组
            $result[] = $item;
        }

        // ✅ 正确返回分页结构：total + rows
        return json([
            'total' => $orders->total(),
            'rows' => $result,
        ]);
    }

    //获取职位列表
    public function position()
    {
        $position = $this->model->getJobOfferPositionList();
        $positionlist = [];
        //获取当前登录的角色
        foreach ($position as $key => $value) {
            $positionlist[] = [
                'value' => $key,
                'name' => $value
            ];
        }
        $this->success('', '', $positionlist);

    }

    /**
     * 获取工作人员列表（根据职位和订单）
     */
    public function worker()
    {
        $positionId = $this->request->get('position', 0);
        $orderId = $this->request->get('order_id', 0);
        if (empty($positionId)) {
            $this->success('', '', []);
        }

        // 获取职位名称
        $positionList = $this->model->getJobOfferPositionList();
        $positionName = isset($positionList[$positionId]) ? $positionList[$positionId] : '';

        if (empty($positionName)) {
            $this->success('', '', []);
        }

        // 查询该职位（角色组）的所有用户
        // $roleUsers = Db::name('admin')
        //     ->alias('admin')
        //     ->join('auth_group_access aga', 'admin.id = aga.uid')
        //     ->join('auth_group ag', 'ag.id = aga.group_id')
        //     ->where('ag.name', $positionName)
        //     ->where('admin.status', 'normal')
        //     ->field('admin.id as value, admin.nickname as name')
        //     ->select();

        // 如果传入了订单ID，优先显示该订单下已分配的人员
        // if (!empty($orderId)) {
        //     // 查询该订单下该职位已分配的人员ID
        //     $assignedUserIds = Db::name('pt_job_offer')
        //         ->alias('offer')
        //         ->join('fa_admin admin', 'admin.id = offer.user_id', 'left')
        //         ->where('order_id', $orderId)
        //         ->where('position', $positionId)
        //         // ->where('offer_status', 2) // 已接受
        //         ->field('admin.id as value, admin.nickname as name')
        //         ->select();
        //     //如果已经有改角色人员 就只显示这个人


        //     if (empty($assignedUserIds)) {
        //         // 如果没有已分配的人员，直接使用角色组用户
        //         $users = $roleUsers;
        //     } else {
        //         $users = $assignedUserIds;
        //     }
        // } else {
        //     // 没有订单ID，直接使用角色组用户
        //     $users = $roleUsers;
        // }
        // 如果传入了订单ID，优先显示该订单下已分配的人员
        $users = [];   
        if (!empty($orderId)) {
            // 查询该订单下该职位已分配的人员ID
            $assignedUserIds = Db::name('pt_job_offer')
                ->alias('offer')
                ->join('fa_admin admin', 'admin.id = offer.user_id', 'left')
                ->where('order_id', $orderId)
                ->where('position', $positionId)
                // ->where('offer_status', 2) // 已接受
                ->field('admin.id as value, admin.nickname as name')
                ->select();
            
            $users = $assignedUserIds ?? [];
            
        } 


        $this->success('', '', $users);

    }

    

    /**
     * 获取工作明细详情（包含工作内容、人员列表、历史记录）
     */
    public function detail()
    {

        $orderId = $this->request->get('order_id');
        $job_id = $this->request->get('job_id');

        if (!$orderId || !$job_id) {
            $this->error('参数不完整');
        }

        $jobModel = new Job();
        //获取订单信息
        $job = $jobModel
            ->with(['order'])
            ->where('id', $job_id)
            ->find();
        if (!$job) {
            $this->error('数据不存在');
        }
        if (!$job['order']) {
            $this->error('订单不存在');
        }
        $lastRecord = Db::name('pt_job_record')->where('job_id', $job['id'])->order('create_time desc')->find();
        //查询的情况
        if (false === $this->request->isPost()) {
            $permission = $this->getPagePermission($lastRecord ,$job['title']);
            // 获取工作内容
            $jobContent = $this->getJobContent($job['title'], $job['id']);
            $row = $jobContent['data'];
            //去除data属性
            unset($jobContent['data']);
            
            // 如果是继续教育类型，传递记录数组
            $educationRecords = [];
            if ($jobContent['job_type_code'] == 1 && is_array($row) && !empty($row)) {
                $educationRecords = $row;
            }
            // 获取人员列表
            //$userList = $this->getUserListData($orderId, $jobContent);

            // 获取历史记录
            $history = $this->getHistoryData($job['id']);


            // 非AJAX请求，返回模板
            $this->view->assign('job',  $job);
            $this->view->assign('job_content', $jobContent);
            $this->view->assign('row', $row);
            $this->view->assign('education_records', $educationRecords);
            // $this->view->assign('user_list', $userList);
            $this->view->assign('history', $history);
            // $this->view->assign('job_id', $job_id);
            $this->view->assign('permission', $permission);

            return $this->view->fetch();
        }

        // 处理POST请求
        $action = $this->request->post('action');
        // 表单隐藏字段提交，优先从 POST 取，回退到 param
        $job_type_code = $this->request->post('job_type_code');
        if ($job_type_code === null) {
            $job_type_code = $this->request->param('job_type_code');
        }
        switch ($action) {
            case 'save':
                // 保存工作内容
                $this->saveJobContent($job, $job_type_code, $lastRecord);
                break;
            case 'back':
                // 取消工作
                $this->backJob($job, $lastRecord);
                break;
            // case 'reassign':
            //     // 重新指定人员
            //     $this->reassignJob($job);
            //     break;
            case 'generate_order':
                // 生成订单
                $this->generateOrder($job_id, $orderId);
                break;

            default:
                $this->error('无效的操作');
        }
    }

    /**
     * 保存工作内容
     */
    private function saveJobContent($job, $job_type_code, $lastRecord)
    {
        // 获取表单数据
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error('没有数据需要保存');
        }

        if (!$params['position_id']) {
            $this->error('请选择工种');
        }

        if (!$params['worker_id']) {
            $this->error('请选择人员');
        }

        //检查最新的记录

        if ($lastRecord) {
           
            if ($lastRecord['worker_id'] != $this->auth->id) {
                $this->error('不是当前工作人员,不能提交');
            }
            //判断角色是否相同
            if ($lastRecord['position_id'] == $params['position_id']) {
                $this->error('选择的角色重复,请重新选择');
            } 
         
        } else {
            //记录为空时,检查是否是组长

            if (!$this->isGroup('组长')) {
                $this->error('无权限,请联系组长提交');
            }
            //检查提交角色是否是组长
            if ($params['position_id'] == 1) {
                $this->error('当前已经是组长,请选择其他角色');
            }
        }
    
        Db::startTrans();
        try {
            //检查job_offer
            $jobOffer = Db::name('pt_job_offer')->where('order_id', $job['order_id'])
                ->where('position', $params['position_id'])
                ->where('user_id', $params['worker_id'])
                ->find();
            if (!$jobOffer) {
                //新增工作邀请
                $jobOffer = [
                    'order_id' => $job['order_id'],
                    'user_id' => $params['worker_id'],
                    'position' => $params['position_id'],
                    'responsibility' => $params['responsibility'],
                    'offer_status' => 2,
                ];
                Db::name('pt_job_offer')->insert($jobOffer);
            }

            $jobUpdate = [

                'worker_id' => $params['worker_id'],
                'worker_name' => $params['worker_name'],
                // 'responsibility' => $params['responsibility'],
                'position_id' => $params['position_id'],
                'position_name' => $params['position_name'],
                'status' => 2
            ];

            // 更新工作内容
            Db::name('pt_job')->where('id', $job['id'])->update($jobUpdate);

            // 插入工作历史
            $maxSeqNo = Db::name('pt_job_record')->where('job_id', $job['id'])->max('seq_no');
            $jobRecord = [
                'job_id' => $job['id'],
                //根据job_id 在jobRecord中找到最大 seq_no 然后加1,如果没有就给1
                'seq_no' => $maxSeqNo ? $maxSeqNo + 1 : 1,
                'submitter_id' => $this->auth->id,
                'submitter_name' => $this->auth->nickname,
                'position_id' => $params['position_id'],
                'position_name' => $params['position_name'],
                'worker_id' => $params['worker_id'],
                'worker_name' => $params['worker_name'],
                'create_time' => date('Y-m-d H:i:s'),
                'options' => $params['options'],
            ];
            Db::name('pt_job_record')->insert($jobRecord);
            //继续教育
            if ($job_type_code == 1) {
                // 获取提交的继续教育记录列表
                $educationRecords = $this->request->post('education_records/a', []);
                
                if (empty($educationRecords)) {
                    $this->error('请至少添加一条继续教育记录');
                }
                
                //找到原有的记录
                $oldIds = Db::name('pt_edu_cont_detail')->where('job_id', $job['id'])->column('id');
                $deleteIds = array_diff($oldIds, array_column($educationRecords, 'id'));
                if($deleteIds) {
                    Db::name('pt_edu_cont_detail')->where('id', 'in', $deleteIds)->delete();
                }
                // 插入新记录
                foreach ($educationRecords as $record) {
                    if (empty($record['platform_id']) || empty($record['year']) || empty($record['total_class_hour'])) {
                        continue; // 跳过空记录
                    }
                    if($record['id']) {
                        //更新记录
                        $eduContDetail = Db::name('pt_edu_cont_detail')->where('id', $record['id'])->find();
                        if ($eduContDetail) {
                            $eduContDetail['platform_id'] = $record['platform_id'];
                            $eduContDetail['year'] = $record['year'];
                            $eduContDetail['total_class_hour'] = $record['total_class_hour'];
                            Db::name('pt_edu_cont_detail')->where('id', $record['id'])->update($eduContDetail);
                        }
                    }else{
                        //新增记录
                        $eduContDetail = [
                            'job_id' => $job['id'],
                            'platform_id' => $record['platform_id'],
                            'year' => $record['year'],
                            'total_class_hour' => $record['total_class_hour'],
                            'archived' => 0,
                            'creator_id' => $this->auth->id,
                        ];
                        Db::name('pt_edu_cont_detail')->insert($eduContDetail);
                    }
                    
          
                }
            }//科研专利等写作 
            else if ($job_type_code == 2) {
                //新增写作明细
                $docDetails = Db::name('pt_doc_details')->where('job_id', $job['id'])->find();
                if (!$docDetails) {
                    $docDetails = [
                        'job_id' => $job['id'],
                        'job_detail_name' => $job['title'],
                    ];
                    Db::name('pt_doc_details')->insert($docDetails);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('保存失败：' . $e->getMessage());
        }

        // 事务提交成功后再返回成功消息
        $this->success('保存成功');
    }
    /**
     * 工作回退
     * @param object $job
     * @param mixed $job_type_code
     * @return void
     */
    private function backJob($job,  $lastRecord)
    {

            //检查最新的记录
            if ($lastRecord) {
                if ($lastRecord['submitter_id'] != $this->auth->id) {
                    $this->error('您无权限回退');
                }
            }

            Db::startTrans();
            try {
              //job_offer 不做变更

              //更新job
              //判断$lastRecord 的序号
                if($lastRecord['seq_no'] == 1) {
                    $jobUpdate = [
                        'worker_id' => null,
                        'worker_name' => null,
                        'position_id' => null,
                        'position_name' => null,
                    ];
                } else {
                    //回退到上一个记录
                    $prevRecord = Db::name('pt_job_record')->where('job_id', $job['id'])->where('seq_no', $lastRecord['seq_no'] - 1)->find();
                    $jobUpdate = [
                        'worker_id' => $prevRecord['worker_id'],
                        'worker_name' => $prevRecord['worker_name'],
                        'position_id' => $prevRecord['position_id'],
                        'position_name' => $prevRecord['position_name'],
                    ];
                }

                // 更新工作内容
                Db::name('pt_job')->where('id', $job['id'])->update($jobUpdate);

                // 删除最新提交的工作历史
                Db::name('pt_job_record')->where('job_id', $job['id'])->where('seq_no', $lastRecord['seq_no'])->delete();

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
          // 事务提交成功后再返回成功消息
        $this->success('保存成功');
    }
    //检查是否是某个角色组
    private function isGroup($groupName)
    {
        $isInGroup = false;
        foreach ((array) $this->auth->getGroups() as $group) {

            if ($group['name'] !== null && $group['name'] === $groupName) {
                $isInGroup = true;
                break;
            }
        }
        return $isInGroup;
    }

    //页面操作权限
    private function getPagePermission($lastRecord, $jobTitle)
    {
        $permission = ['edit' => false, 'back' => false, 'reassign' => false,'order' => false];
        $needOrder = ['继续教育','科研','论文','著作','专利','教育经历'] ;
        //如果$jobTitle在$needOrder中,则可以生成订单
        if(in_array($jobTitle, $needOrder)) {
            $permission['order'] = true;
        }

        //如果当前用户是组长或总务,则可以重置 //如果当前用户是组长或总务,则可以重置
        $isLeader = $this->isGroup('组长');
        if ($isLeader || $this->isGroup('总监')) {
            $permission['reassign'] = true;
        }
        //如果$lastRecord为空则组长有编辑权限
        if ($lastRecord) {
            if ($lastRecord['worker_id'] == $this->auth->id) {
                $permission['edit'] = true;
            }
            if ($lastRecord['submitter_id'] == $this->auth->id) {
                $permission['back'] = true;
            }
        } else {
            if ($isLeader) {
                $permission['edit'] = true;
            }
        }


        return $permission;
    }




    /**
     * 生成订单
     */
    private function generateOrder($job_id, $orderId)
    {

        $this->error('功能开发中,敬请期待');
        // 获取表单数据
        $data = $this->request->post();

        // 验证数据
        if (empty($data)) {
            $this->error('没有数据需要处理');
        }

        // 生成订单逻辑
        // TODO: 实现具体的订单生成逻辑

        $this->success('订单生成成功');
    }


    /**
     * 获取历史记录数据
     */
    private function getHistoryData($jobId)
    {
        $history = Db::name('pt_job_record')
            ->field('id,title,seq_no,submitter_name,worker_name,position_name,options,create_time')
            ->where('job_id', $jobId)
            ->order('create_time desc')
            ->select();


        return $history;
    }

    /**
     * 根据工作类型生成内容
     */
    private function getJobContent($jobType, $jobId)
    {

        //'继续教育'为一类;'科研',  '论文', '著作', '专利'为2类,其他为3类,总共17项
        //['教育经历', '工作经历', '继续教育', '学术兼职', '项目获奖', '个人荣誉', '科研', '工程业绩', '论文', '著作', '专利', '标准规程', '成功运用推广', '资质', '奖惩', '指导参赛', '年度考核表'];

        // 根据工作类型返回不同的内容
        $contentMap = [
            '教育经历' => 3,
            '工作经历' => 3,
            '继续教育' => 1,
            '学术兼职' => 3,
            '项目获奖' => 3,
            '个人荣誉' => 3,
            '科研' => 2,
            '工程业绩' => 3,
            '论文' => 2,
            '著作' => 2,
            '专利' => 2,
            '标准规程' => 3,
            '推广' => 3,
            '资质' => 3,
            '奖惩' => 3,
            '指导参赛' => 3,
            '考核表' => 3
        ];
        $jobTypeCode = $contentMap[$jobType] ?? 3;
        $jobContent['job_type_code'] = $jobTypeCode;
        $jobContent['job_type'] = $jobType;
        if ($jobTypeCode == 1) {
            //获取继续教育的信息
            $jobContent['data'] = $this->getContinuingEducationContent($jobId);
        } elseif ($jobTypeCode == 2) {
            //获取科研的信息
            $jobContent['data'] = $this->getResearchContent($jobId);
        } elseif ($jobTypeCode == 3) {
            //获取其他的信息
            $jobContent['data'] = $this->getOtherContent($jobId);
        } else {
            $jobContent['data'] = [];
        }

        return $jobContent;
    }

    private function getContinuingEducationContent($jobId)
    {
        $ptEduContDetails = Db::name('pt_edu_cont_detail')
            ->alias('detail')
            ->join('pt_edu_platform platform', 'detail.platform_id = platform.id', 'left')
            ->where('detail.job_id', $jobId)
            ->where('detail.archived', 0)
            ->field('detail.*, platform.platform_name')
            ->order('detail.year desc, detail.id desc')
            ->select();
        return $ptEduContDetails ?: [];
    }

    private function getResearchContent($jobId)
    {
        //查询 pt_documents ,写作明细多条
        $documents = Db::name('pt_doc_details')
            ->where('job_id', $jobId)
            ->field('id,topic_title,topic_selected,patent_sign_type,patent_sign_name')
            ->select();
        return $documents;

    }

    private function getOtherContent($jobId)
    {
        //查询 pt_job_content
        // $content = Db::name('pt_job_content')
        //     ->where('job_id', $jobId)
        //     ->find();
        return [];
    }

    /**
     * 重新指定人员页面
     */
    public function reassign()
    {
        // Db类应该在文件顶部导入，这里直接使用
        
        $order_id = $this->request->get('order_id', $this->request->post('order_id'));

        if (!$order_id) {
            $this->error('参数不完整');
        }
        // 查询的情况
        $position = $this->model->getJobOfferPositionList();
        if (false === $this->request->isPost()) {
            
            //根据岗位查询出对应的人员
           $role_users = Db::name('admin')                    // 对应 fa_admin 表
            ->alias('admin')                              // 给 admin 表起别名 a
            ->join('auth_group_access aga', 'admin.id = aga.uid')   // 使用 a.id
            ->join('auth_group ag', 'ag.id = aga.group_id')     // 使用 ag.id
            ->where('ag.name', 'in', $position)             // 按角色组名称过滤
            ->where('admin.status', 'normal')             // 状态为 normal
            ->field('admin.id, admin.nickname, ag.name as group_name')
            ->select();
            //统计每个角色下有多少user ,key 为group_name ,value为userlist
            $group_users = $this->groupUsersByRole($role_users);
            $jobOffer = [];
            // 当前职位-人员映射与责任类型
            $currentAssignments = $this->model
                ->where('order_id', $order_id)
                ->column('user_id', 'position');
            $currentResponsibilities = $this->model
                ->where('order_id', $order_id)
                ->column('responsibility', 'position');
            foreach ($position as $key => $value) {
                $currentWorkerId = isset($currentAssignments[$key]) ? $currentAssignments[$key] : '';
                $currentWorkerName = '';
                if ($currentWorkerId && isset($group_users[$value])) {
                    foreach ($group_users[$value] as $user) {
                        if ($user['id'] == $currentWorkerId) {
                            $currentWorkerName = $user['nickname'];
                            break;
                        }
                    }
                }
                $jobOffer[] = [
                    'position_id' => $key,
                    'position_name' => $value,
                    'users' => $group_users[$value] ?? [],
                    'current_worker_id' => $currentWorkerId,
                    'current_worker_name' => $currentWorkerName,
                    'current_responsibility' => isset($currentResponsibilities[$key]) ? intval($currentResponsibilities[$key]) : 0,
                ];
                
            }
         
            $this->view->assign('jobOffer', $jobOffer);
            $this->view->assign('order_id', $order_id);
            $this->view->assign('currentAssignments', $currentAssignments);
            return $this->view->fetch();
        }
        // 处理POST请求
        $workers = $this->request->post('row/a');
        $hasUpdate = $this->request->post('has_update');
        if (empty($workers)) {
            $this->error('请选择需要更新的人员');
        }
   
        if($hasUpdate == 0){
            $this->success('保存成功');
        }
       
        Db::startTrans();
        try {
             //删除原有的分配记录 不删除组长的
            Db::name('pt_job_offer')->where('order_id', $order_id)->where('position', '>', 1)->delete();
            foreach ($workers as $item) {
         
        
                if (empty($item['position']) || empty($item['user_id'])) {
                    continue;
                }
                if ($position == 1) {
                    continue; // 组长不可重新指定
                }
              
                //新增分配记录
                $jobOffer = [
                    'order_id' => $order_id,
                    'position' => $item['position'],
                    'user_id' => $item['user_id'],
                    'responsibility' => $item['responsibility'],
                    'offer_status' => 2,
                ];
                Db::name('pt_job_offer')->insert($jobOffer);

              
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('人员更新失败: ' . $e->getMessage());
        }

        $this->success('人员更新成功');
    }

  

 
    /**
     * 按角色分组用户数据
     * @param array $users 用户数据数组
     * @return array 按角色分组的用户数据
     */
    private function groupUsersByRole($users)
    {
        $group_users = [];

        foreach ($users as $user) {
            $group_name = $user['group_name'];

            // 如果该角色组还不存在，初始化
            if (!isset($group_users[$group_name])) {
                $group_users[$group_name] = [];
            }

            // 检查用户是否已存在（避免重复）
            $exists = false;
            foreach ($group_users[$group_name] as $existing_user) {
                if ($existing_user['id'] == $user['id']) {
                    $exists = true;
                    break;
                }
            }

            // 如果用户不存在，添加到该角色组
            if (!$exists) {
                $group_users[$group_name][] = [
                    'id' => $user['id'],
                    'nickname' => $user['nickname']
                ];
            }
        }

        return $group_users;
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
